#!/usr/bin/env python

#################################################################################
#
# Copyright (c) 2006 Michigan State University
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
#################################################################################

#################################################################################
#
#	Author:
#		Nathan Collins <npcollins@gmail.com>
#
#################################################################################

"""
Parse and detect record languges.
"""

import re
from querymgr import *

class langParse:
	def __init__(self):
		self.langDict = {}
		self.revDict = {}

	def getLangDict(self):
		# retrieve available languages from harvestLanguage
		select = "SELECT langCode, langDesc, langComm FROM harvestLanguage;"
		results = dbquery(select)

		for result in results:
			self.langDict[result['langCode'].lower()] = ( result['langDesc'].lower(),result['langComm'].lower() )

		# generate reverse language lookup
		rev = re.compile(r'^(\w+-?\w*)$') # skip variations and dated languages for now
		for k,v in self.langDict.iteritems():
			v1,v2 = v
			match = rev.search(v1)
			if match:
				self.revDict[match.groups()[0].lower()] = v2.lower()
			self.revDict[k.lower()]	= v2.lower()
			# drop common
			self.langDict[k] = v1

	def parseLang(self,langStr):
		# parse string and determine language(s)
		# special cases (todo: make cases a readable file)
		special = { 	'ASL' : 'eng',
				'GB' : 'eng',
				'N/A' : '',
				'?' : '' }

		# delimiters
		split = re.compile(r':|;|,|\s|@|\]|\[|"|_\w+')
		# localization form
		local = re.compile(r'(\w\w\w?)_\w+')

		# split language string
		langList = split.split(langStr)

		# swap codes in for words using reverse lookup
		for index in range(0,len(langList)):
			if self.revDict.has_key(langList[index].lower()):
				langList[index] = self.revDict[langList[index].lower()]

		# determine languages
		langs = {}
		for word in langList:
			if self.langDict.has_key(word):
				langs[word] = word

		# if empty list, returns empty string
		return ' '.join(list(langs))


# eof

